package com.zx.account.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zx.account.dao.ATypeDetailMapper;
import com.zx.account.dao.ATypeMapper;
import com.zx.account.entity.AType;
import com.zx.account.entity.ATypeDetail;
import com.zx.account.model.ATypeDetailDto;
import com.zx.account.model.ATypeDto;
import com.zx.account.service.ATypeService;
import com.zx.util.BeanCopyUtil;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

@Service
public class ATypeServiceImpl implements ATypeService {

    @Autowired
    private ATypeMapper aTypeMapper;

    @Autowired
    private ATypeDetailMapper aTypeDetailMapper;

    @Override
    public AType getById(int id) {
        return aTypeMapper.selectById(id);
    }

    @Override
    public List<AType> getAll() {
        return aTypeMapper.selectList(Wrappers.lambdaQuery());
    }

    @Override
    public boolean insert(AType t) {
        return aTypeMapper.insert(t) > 0;
    }

    @Override
    public boolean update(AType t) {
        return aTypeMapper.updateById(t) > 0;
    }

    @Override
    public boolean insert(ATypeDetail t) {
        return aTypeDetailMapper.insert(t) > 0;
    }


    @Override
    public List<ATypeDto> getByUserId(int userId) {
        List<AType> typeList = aTypeMapper.selectList(Wrappers.<AType>lambdaQuery().eq(AType::getUserId, userId));
        List<ATypeDto> resTypeList = BeanCopyUtil.copy(typeList, AType.class, ATypeDto.class);

        List<ATypeDetail> details = this.aTypeDetailMapper
                .selectList(Wrappers.<ATypeDetail>lambdaQuery().eq(ATypeDetail::getUserId, userId));
        if (CollectionUtils.isEmpty(details)) {
            return resTypeList;
        }

        List<ATypeDetailDto> resDetails = BeanCopyUtil.copy(details, ATypeDetail.class, ATypeDetailDto.class);
        Map<Integer, List<ATypeDetailDto>> tMap = resDetails.stream()
                .collect(Collectors.groupingBy(ATypeDetailDto::getTId));
        for (ATypeDto typeDto : resTypeList) {
            List<ATypeDetailDto> detailDtos = tMap.getOrDefault(typeDto.getId(), Collections.emptyList());
            typeDto.setDetails(detailDtos);
        }

        return resTypeList;
    }

    @Override
    public List<ATypeDetailDto> getDetailByUserId(int userId) {
        List<ATypeDetail> typeDetailList = aTypeDetailMapper
                .selectList(Wrappers.<ATypeDetail>lambdaQuery().eq(ATypeDetail::getUserId, userId));
        List<ATypeDetailDto> resTypeDetailList = BeanCopyUtil
                .copy(typeDetailList, ATypeDetail.class, ATypeDetailDto.class);
        return resTypeDetailList;
    }

}
